import dataPreferences from '@ohos.data.preferences';
import { BusinessError } from '@ohos.base';
import { GlobalContext, GlobalContextConstants } from '../common/GlobalContext'

let preferences: dataPreferences.Preferences | null = null;

export default class PreferencesUtils {
  private static RAWFILE_RESOURCES_NAME:string = "rawfileResources";

  private static options: dataPreferences.Options = { name: PreferencesUtils.RAWFILE_RESOURCES_NAME };

  public static loadPreferences(){
    if(preferences === null){
      preferences = dataPreferences.getPreferencesSync(GlobalContext.loadGlobalThis(GlobalContextConstants.ABILITY_CONTEXT), PreferencesUtils.options);
    }
  }

  /**
   * put key and value in preferences
   * @param key
   * @param value
   */
  public static put(key:string, value:any): boolean{
    PreferencesUtils.loadPreferences();
    
    let result:boolean = false;
    if (preferences.hasSync(key)) {
      result = false;
    }
    preferences.putSync(key, value);
    preferences.flush();
    result = true;
    return result;
  }
  
  public static get(key:string): any {
    PreferencesUtils.loadPreferences();
    if (!preferences.hasSync(key)) {
      return "";  
    }
    let value:dataPreferences.ValueType = preferences.getSync(key, 'default');
    return value;
  }
  
  public static hasSync(key:string): boolean{
    PreferencesUtils.loadPreferences();
    return preferences.hasSync(key);
  }
  
  public static delete(key:string){
    PreferencesUtils.loadPreferences();
    preferences.deleteSync(key);
    preferences.flush();
  }
  
  public static clear(){
    PreferencesUtils.loadPreferences();
    preferences.clearSync();
    preferences.flush();
  }

}